//
//  KRContactsViewController.m
//  KingrayTone_ios
//
//  Created by XiongYingqi on 14-5-16.
//  Copyright (c) 2014年 XiongYingqi. All rights reserved.
//

#import "KRContactsViewController.h"
#import "KRAppDelegate.h"
#import "DDLog.h"
#import "SKSTableViewCell.h"
#import "XYQDrawPersonImage.h"
#import "KRChatViewController.h"
#import "KRChatViewController2.h"

#if DEBUG
static const int ddLogLevel = LOG_LEVEL_VERBOSE;
#else
  static const int ddLogLevel = LOG_LEVEL_INFO;
#endif


@interface KRContactsViewController ()

@end

@implementation KRContactsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    [view removeFromSuperview];
}

- (void)viewDidLoad {


    [super viewDidLoad];

//    [[self.tableView tableHeaderView] removeFromSuperview];
//    [[self.tableView headerViewForSection:0] removeFromSuperview];


    NSFetchedResultsController *fetchedGroupResultsControllerVar = [self fetchedResultsController];
    NSArray *groups = [fetchedGroupResultsControllerVar fetchedObjects];
    NSLog(@"groups ======= %@", groups);

    NSLog(@"tableView ==== %@", self.tableView);

    self.tableView.SKSTableViewDelegate = self;

    // In order to expand just one cell at a time. If you set this value YES, when you expand an cell, the already-expanded cell is collapsed automatically.
//    self.tableView.shouldExpandOnlyOneCell = YES;

    self.navigationItem.title = @"联系人";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收起"
                                                                              style:UIBarButtonItemStylePlain
                                                                             target:self
                                                                             action:@selector(collapseSubrows)];
    // Do any additional setup after loading the view from its nib.

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//- (NSFetchedResultsController *)fetchedGroupResultsController
//{
//    if (fetchedGroupResultsController == nil)
//    {
//        NSManagedObjectContext *moc = [[KRAppDelegate appDelegate] managedObjectContext_roster];
//
//        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPGroupCoreDataStorageObject"
//                                                  inManagedObjectContext:moc];
//
//        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//        //NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
//
//        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];
//
//        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//        [fetchRequest setEntity:entity];
//        [fetchRequest setSortDescriptors:sortDescriptors];
//        [fetchRequest setFetchBatchSize:10];
//
//        fetchedGroupResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
//                                                                            managedObjectContext:moc
//                                                                              sectionNameKeyPath:@"name"
//                                                                                       cacheName:nil];
//        [fetchedGroupResultsController setDelegate:self];
//
////        [sd1 release];
////        //[sd2 release];
////        [fetchRequest release];
//
//        NSError *error = nil;
//        if (![fetchedGroupResultsController performFetch:&error])
//        {
//            NSLog(@"Error performing fetch: %@", error);
//        }
//
//    }
//
//    return fetchedGroupResultsController;
//}

//- (NSFetchedResultsController *)fetchedResultsController {
//    if (fetchedResultsController == nil) {
//        NSManagedObjectContext *moc = [[KRAppDelegate appDelegate] managedObjectContext_roster];
//
//        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPUserCoreDataStorageObject"
//                                                  inManagedObjectContext:moc];
//
//        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"sectionNum" ascending:YES];
//        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];
//
//        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, sd2, nil];
//
//        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//        [fetchRequest setEntity:entity];
//        [fetchRequest setSortDescriptors:sortDescriptors];
//        [fetchRequest setFetchBatchSize:10];
//
//        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
//                                                                       managedObjectContext:moc
//                                                                         sectionNameKeyPath:@"sectionNum"
//                                                                                  cacheName:nil];
//        [fetchedResultsController setDelegate:self];
//
//
//        NSError *error = nil;
//        if (![fetchedResultsController performFetch:&error]) {
//            DDLogError(@"Error performing fetch: %@", error);
//        }
//
//    }
//
//    return fetchedResultsController;
//}

- (NSFetchedResultsController *)fetchedResultsController {
    if (fetchedResultsController == nil) {
        NSManagedObjectContext *moc = [[KRAppDelegate appDelegate] managedObjectContext_roster];

        NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPGroupCoreDataStorageObject"
                                                  inManagedObjectContext:moc];

        NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
//        NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:@"displayName" ascending:YES];

        NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1, nil];

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        [fetchRequest setEntity:entity];
        [fetchRequest setSortDescriptors:sortDescriptors];
        [fetchRequest setFetchBatchSize:10];

        fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                       managedObjectContext:moc
                                                                         sectionNameKeyPath:@"name"
                                                                                  cacheName:nil];
        [fetchedResultsController setDelegate:self];


        NSError *error = nil;
        if (![fetchedResultsController performFetch:&error]) {
            DDLogError(@"Error performing fetch: %@", error);
        }

    }

    return fetchedResultsController;
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {

    [[self tableView] reloadData];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([[self fetchedResultsController] fetchedObjects].count > 0) {
        return 1;
    } else {
        return 0;
    }
}


- (CGFloat)tableView:(SKSTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Section: %d, Row:%d, Subrow:%d", indexPath.section, indexPath.row, indexPath.subRow);
}

- (void)tableView:(SKSTableView *)tableView didSelectSubRowAtIndexPath:(NSIndexPath *)indexPath {
    XMPPUserCoreDataStorageObject *user = [self getUserByIndexPath:indexPath];
    KRChatViewController *chatViewController = [KRChatViewController getRoom:user];
//    self.navigationControlle
    chatViewController.hidesBottomBarWhenPushed = true;// push之前隐藏tabBar
    [self.navigationController pushViewController:chatViewController animated:YES];
//    [chatViewController viewDidLoad];

    NSLog(@"Section: %d, Row:%d, Subrow:%d", indexPath.section, indexPath.row, indexPath.subRow);
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex {
//    NSArray *sections = [[self fetchedResultsController] sections];

//    if (sectionIndex < [sections count]) {
//        id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:sectionIndex];
//        return sectionInfo.numberOfObjects;
//    }
//    NSLog(@"numberOfRowsInSection   [[[self fetchedResultsController] fetchedObjects] =========== %@", [[self fetchedResultsController] fetchedObjects]);
//    NSLog(@"numberOfRowsInSection   [[self fetchedResultsController] fetchedObjects].count =========== %d", [[self fetchedResultsController] fetchedObjects].count);

//    NSArray *array = [[self fetchedResultsController] fetchedObjects];
//    for (int j = 0; j < array.count; j++) {
//        XMPPGroupCoreDataStorageObject *group = [array objectAtIndex:j];
//        NSLog(@"a =========== %@", group.name);
//    }


    return [[self fetchedResultsController] fetchedObjects].count;
}



////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark UITableViewCell helpers
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)configurePhotoForCell:(UITableViewCell *)cell user:(XMPPUserCoreDataStorageObject *)user {
    // Our xmppRosterStorage will cache photos as they arrive from the xmppvCardAvatarModule.
    // We only need to ask the avatar module for a photo, if the roster doesn't have it.

    if (user.photo != nil) {
        cell.imageView.image = user.photo;
    } else {
        NSData *photoData = [[[KRAppDelegate appDelegate] xmppvCardAvatarModule] photoDataForJID:user.jid];

        if (photoData != nil) {

            cell.imageView.image = [UIImage imageWithData:photoData];
        }
        else {
//            cell.imageView.image = [UIImage imageNamed:@"defaultPerson"];
            cell.imageView.image = [[[XYQDrawPersonImage alloc] init] getPersonImage:user.displayName];
//            cell.imageView.image = [[[XYQDrawPersonImage alloc] init] getImage];


        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"SKSTableViewCell";

//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    SKSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


    if (cell == nil) {
        cell = [[SKSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    XMPPGroupCoreDataStorageObject *groupCoreDataStorageObject = [[[self fetchedResultsController] fetchedObjects] objectAtIndex:indexPath.row];

//    NSLog(@"groupCoreDataStorageObject.name =========== %@", groupCoreDataStorageObject.name);
    cell.textLabel.text = groupCoreDataStorageObject.name;


//    if (indexPath.row == 1)
    cell.expandable = YES;
//    else
//        cell.expandable = NO;


    return cell;
}


/**
* SKSTableView
*/
- (NSInteger)tableView:(SKSTableView *)tableView numberOfSubRowsAtIndexPath:(NSIndexPath *)indexPath {
//    static NSString *CellIdentifier = @"UITableViewCell";
//
////    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//
//    SKSTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//
//
//    if (cell == nil) {
//        cell = [[SKSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//    }
//
//
//    NSString *name = [[[self fetchedResultsController] objectAtIndexPath:indexPath] user];
//
//    cell.textLabel.text = name;

    NSArray *groups = [[self fetchedResultsController] fetchedObjects];
    NSUInteger row = indexPath.row;
    XMPPGroupCoreDataStorageObject *group = [groups objectAtIndex:row];


//    NSLog(@"indexPath.row ============== %d", indexPath.row);
//    NSLog(@"users.count ============== %d", group.users.count);

    return group.users.count;
}

- (UITableViewCell *)tableView:(SKSTableView *)tableView cellForSubRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"UITableViewCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    XMPPUserCoreDataStorageObject *user = [self getUserByIndexPath:indexPath];

    cell.textLabel.text = [NSString stringWithFormat:@"%@", user.displayName];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    [self configurePhotoForCell:cell user:user];

    return cell;

//    return nil;
}


/**
* 根据indexPath获取用户
*/
- (XMPPUserCoreDataStorageObject *)getUserByIndexPath:(NSIndexPath *)indexPath {
    XMPPGroupCoreDataStorageObject *groupCoreDataStorageObject = [self getGroupByIndexPath:indexPath];

//    NSLog(@"groupCoreDataStorageObject ============ %@", groupCoreDataStorageObject);
//    NSLog(@"groupCoreDataStorageObject.users.count ============ %@", groupCoreDataStorageObject.users);


    NSEnumerator *enumerator = groupCoreDataStorageObject.users.objectEnumerator;
    XMPPUserCoreDataStorageObject *user = nil;

    int i = 0;

//    NSLog(@"indexPath ============ %@", indexPath.length);
//    NSLog(@"indexPath ============ %@", indexPath);
//    NSLog(@"indexPath ============ %@", indexPath.subRow);
    for (NSObject *object in enumerator) {
        user = object;
//        NSLog(@"indexPath.subRow ======= %d", indexPath.subRow);
        if (i >= indexPath.subRow - 1) {
            break;
        }
        i++;
    }
    return user;
}

/**
* 根据indexPath获取分组
*/
- (XMPPGroupCoreDataStorageObject *)getGroupByIndexPath:(NSIndexPath *)indexPath {
    XMPPGroupCoreDataStorageObject *groupCoreDataStorageObject = [[[self fetchedResultsController] fetchedObjects] objectAtIndex:indexPath.row];
    return groupCoreDataStorageObject;
}


#pragma mark - Actions

- (void)collapseSubrows {
    [self.tableView collapseCurrentlyExpandedIndexPaths];
}


@end
